package com.jues.huichain.jsweb;

import android.Manifest;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.text.TextUtils;
import android.webkit.JavascriptInterface;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonSyntaxException;
import com.vondear.rxtool.RxClipboardTool;
import com.vondear.rxtool.RxSPTool;

import health.lm.com.component_base.popup.share.SharePopUtil;
import health.lm.com.component_base.scan.ScanUtil;
import health.lm.com.component_base.webview.WebAcitivity;
import health.lm.com.data.App;
import health.lm.com.data.AppModel;
import health.lm.com.find.pop.EvaluationPopUtil;
import health.lm.com.network.callback.SimpleCallBack;
import health.lm.com.router.ARouterConstant;

/**
 * Created by Android Studio .
 * Project：hlian health.lm.com.component_base.webview
 * Date：2019/8/28 15:52
 * Introduce：带有JS交互的WebView 页面 （新闻详情、活动详情、智库详情等）
 */
@Route(path = ARouterConstant.JSWebActivity)
public class JSWebActivity extends WebAcitivity {
    @Override
    public void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
    }

    @Override
    protected void setJsInterface() {
        super.setJsInterface();
        mAgentWeb.getJsInterfaceHolder().addJavaObject("android", new JSInteraction());
    }

    /**
     * JS交互方法类
     */
    public class JSInteraction {

        /**
         * 返回token 信息
         *
         * @return token
         */
        @JavascriptInterface
        public String token() {
            return App.getModel().getAccess_token();
        }

        /**
         * 能量
         * @param id 文章ID
         */
        @JavascriptInterface
        public void energy(String id) {
            JsWebModel.getInstance().energy(id, new SimpleCallBack<EnergyEntity>() {
                @Override
                public void onSuccess(EnergyEntity pEntity) {
                    mAgentWeb.getJsAccessEntrace().quickCallJs("energy('" + pEntity.getEnergy_num() + "')");
                }
            });
        }

        /**
         * 下载文件
         *
         * @param url 文件地址
         */
        @JavascriptInterface
        public void downImg(String url) {
            LogUtils.d("下载文件");
            DownFileEntity entity = new GsonBuilder().create().fromJson(url, DownFileEntity.class);
            JsWebModel.getInstance().downLoad(entity, context, linearLayout);
        }

        /**
         * 新闻点赞
         *
         * @param id 新闻ID
         */
        @JavascriptInterface
        public void zan(String id) {
            JsWebModel.getInstance().zan(id, new SimpleCallBack<Object>() {
                @Override
                public void onSuccess(Object pO) {
                    mAgentWeb.getJsAccessEntrace().quickCallJs("zanResult()");
                }
            });
        }

        /**
         * 新闻、活动分享
         *
         * @param shareUrl 新闻ID
         */
        @JavascriptInterface
        public void share(String title, String desc, String shareUrl) {
            String image = "http://admin.sdliumaikeji.com/static//images/logo.png";
            runOnUiThread(() -> {
                SharePopUtil.getInstance().showContent(context, linearLayout, title, desc, image, shareUrl);
            });
        }

        /**
         * 分享接口 红包分享
         *
         * @param json 分享json串
         */
        @JavascriptInterface
        public void share2(String json) {
            if (TextUtils.isEmpty(json)) return;
            try {
                Gson gson = new GsonBuilder().create();
                ShareEntity.ResultDataBean dataBean = gson.fromJson(json, ShareEntity.ResultDataBean.class);
                runOnUiThread(() -> {
                    SharePopUtil.getInstance().showContent(context, linearLayout
                            , dataBean.getTitle(), dataBean.getContent()
                            , dataBean.getAvatar(), dataBean.getUrl());
                });
            } catch (JsonSyntaxException e) {
                e.printStackTrace();
            }
        }

        @JavascriptInterface
        public void copy(String content) {
            RxClipboardTool.copyText(context, content);
            ToastUtils.showShort("复制成功");
        }

        /**
         * 参加
         *
         * @param activity_id 活动ID
         */
        @JavascriptInterface
        public void activityJoin(String activity_id) {
            RxSPTool.putString(context, AppModel.my_activity_id, activity_id);
            //跳转支付
            withValueActivity(ARouterConstant.ActivityPayActivity).withString("id", activity_id).navigation();
        }

        /**
         * 查看二维码
         *
         * @param activity_id 活动ID
         */
        @JavascriptInterface
        public void viewQRCode(String activity_id) {
            RxSPTool.putString(context, AppModel.my_activity_id, activity_id);
            //跳转查看二维码页面
            withValueActivity(ARouterConstant.QrCodeActivity).withString("id", activity_id).navigation();
        }

        /**
         * 评价
         *
         * @param activity_id 活动ID
         */
        @JavascriptInterface
        public void evaluation(String activity_id) {
            RxSPTool.putString(context, AppModel.my_activity_id, activity_id);
            //popup 评价
            runOnUiThread(()->{
                EvaluationPopUtil.getInstance().init(context, linearLayout, activity_id);
            });
        }

        /**
         * 二维码扫描
         */
        @SuppressLint("CheckResult")
        @JavascriptInterface
        public void capture() {
            LogUtils.d("扫码");
            rxPermissions.request(Manifest.permission.CAMERA, Manifest.permission.VIBRATE).subscribe(b -> {
                ScanUtil.getInstance().homeNavScan(context, data -> {
                    //处理扫描结果（在界面上显示）
                    if (null == data) return;
                    mAgentWeb.getJsAccessEntrace().quickCallJs("setaccounts('" + data + "')");
                });
            });
            //String[] strings = {};
            //boolean isCamera = Function.lacksPermissions(mContext, strings);
            //if (!isCamera) {
            //    Intent intent = new Intent(MainActivity.this, CaptureActivity.class);
            //    startActivityForResult(intent, CAPTURE_CODE);
            //} else
            //    ActivityCompat.requestPermissions(MainActivity.this, strings, CAPTURE_PERMISSION_CODE);
        }
    }

    @Override
    protected void onResume() {
        if (mAgentWeb != null) {
            mAgentWeb.getWebLifeCycle().onResume();
            LogUtils.e("刷新URL");
            mAgentWeb.getUrlLoader().reload();
        }
        super.onResume();
    }
}
